/**
 * ElectronExchanger Server Code File
 * 
 * File:        server_main.c
 * Brief:       BRIEF
 * Author:      Chen Kangbing
 * Email:       ckblau@outlook.com
 * Modified:    2020/09/14 15:52:41
 *
 */


#include "server_main.h"
#include "cliarg_helper.h"
#include "thread_helper.h"
#include "transaction.h"
#include "db_helper.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


ServerSocketTypeDef *init_server(int argc, char **argv) {
    ServerSocketTypeDef *psrv;
    int ret;
    psrv = malloc(sizeof(ServerSocketTypeDef));
    memset(psrv, 0, sizeof(ServerSocketTypeDef));

    ret = parse_arg(psrv, argc, argv);
    if (ret != 0) {
        exit(1);
    }

    ret = init_socket_server(psrv);
    if (ret != 0) {
        exit(2);
    }

    ret = mysql_OpenSql();
    if (ret != 0) {
        exit(3);
    }

    srand((unsigned)time(NULL));

    return psrv;
}

void deinit_server(ServerSocketTypeDef *psrv) {
    deinit_socket_server(psrv);
    free(psrv);
    mysql_CloseSql();
}

int main(int argc, char **argv) {
    ServerSocketTypeDef *psrv;
    psrv = init_server(argc, argv);

    while (1) {
        TransmissionTypeDef *ptrans;
        ptrans = create_transmission();

        if (loop_listen(psrv, ptrans) != 0) {
            destroy_transmission(ptrans);
            continue;
        }

        thread_start(&ptrans->thread_tid, transaction_main, (void *)ptrans);        
    }

    deinit_server(psrv);
    return 0;
}
